<?php

$data = '"LINE1","LINE2","LINE3","LINE4","APPELASHN","SUBS_NUM","SURNAME","AN1","TITLE1","AN2","TITLE2","AN3","TITLE3","AN4","TITLE4","AN5","TITLE5","AN6","TITLE6"' . "\n";

$prev_subscriber_id = "";
$count = 6;

foreach ($loans->result() as $loan)
{
	if ($loan->subscriber_id != $prev_subscriber_id)
	{
        for ( $i = 0; $i < (6 - $count); $i++ )
			$data .= ',"",""';
            
		if ($prev_subscriber_id)
			$data .= "\n";
			
		$data .=	'"' . $loan->subscriber_title . ' ' . $loan->initials . ' ' . $loan->last_name . '",' .	// Line 1 (Title Initials Last_Name)
					'"' . $loan->address1 . '",' .													// Line 2 (Address1)
					'"' . $loan->suburb . ', ' . $loan->post_code . '",' .													// Line 3 (Suburb)
					'"' . $loan->address2 . '",' .													// Line 4 (Address2)
					'"' . $loan->subscriber_title . ' ' . $loan->last_name . '",' .							// Line 5 (Title Last_Name)
					'"' . $loan->subscriber_id . '",' .												// Line 6 (Subscriber_ID)
					'"' . $loan->last_name . '"';													// Line 7 (Last_Name)
					
		$prev_subscriber_id = $loan->subscriber_id;
		$count = 0;
	}

	// Only output maximum of 6 loans to csv 
	if ($count < 6)
		$data .= ',"' . $loan->access_id . '","' . $loan->title . '"';
	
	$count++;
}

force_download('overdue_loans_mail_merge.csv', $data); 
?>